package com.wenjiang.controller;

import com.wenjiang.common.annotation.RequireToken;
import com.wenjiang.common.annotation.TokenUserId;
import com.wenjiang.common.lang.Result;
import com.wenjiang.service.MallCartService;
import com.wenjiang.common.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/mallCart")
public class MallCartController {

    @Autowired
    MallCartService mallCartService;


    //查询用户的购物车
    @RequireToken
    @RequestMapping("/getUserCart")
    public Object getUserCart(HttpServletRequest request ){
        //获取用户id
        String token = request.getHeader("token");
        Long userId = JWTUtil.getUserId(token);


        Result mallUserCart = mallCartService.getMallUserCart(userId.toString());

        return mallUserCart;

    }


    //添加商品到购物车
    @RequireToken
    @RequestMapping("/addGoodCart/{goodId}")
    public  Object addGoodToCart(HttpServletRequest request, @PathVariable("goodId") String goodId){
        //获取用户id
        String token = request.getHeader("token");
        Long userId = JWTUtil.getUserId(token);

        Result result = mallCartService.addGoodToCart(userId.toString(), goodId);

        return result;

    }


    //增加购买数量
    @RequireToken
    @RequestMapping("/addGoodCount/{goodId}")
    public  Object addGoodCount(HttpServletRequest request, @PathVariable("goodId")String goodId){
        //获取用户id
        String token = request.getHeader("token");
        Long userId = JWTUtil.getUserId(token);

        mallCartService.addGoodCount(userId.toString(),goodId);

        return Result.succ(null);
    }


    //减少购买数量
    @RequireToken
    @RequestMapping("/subGoodCount/{goodId}")
    public  Object subGoodCount(HttpServletRequest request, @PathVariable("goodId")String goodId){
        //获取用户id
        String token = request.getHeader("token");
        Long userId = JWTUtil.getUserId(token);

        mallCartService.subGoodCount(userId.toString(),goodId);

        return Result.succ(null);
    }

    //删除购物车的商品(设置两个参数就可以接收对数组了)
    @RequireToken
    @RequestMapping(value = "/delGoodCart" )
    public void delGoodCart(HttpServletRequest request , @RequestParam("checkedGood") String[] delGoodIds){


        //获取用户id
        String token = request.getHeader("token");
        Long userId = JWTUtil.getUserId(token);

        //遍历选中的商品

        for(String item:delGoodIds){
            mallCartService.delGood(userId.toString(),item.toString());
        }

    }

}
